function getUrl(){
    var url = window.location.href;
    var path = window.location.pathname;
    var search = window.location.search;
    url = url.replace(path,"/");
    url = url.replace(search,"")
    return url;
}

(function ($) {

    //扩展方法获取url参数
    $.getUrlParam = function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }

    //得到url参数
    var urltype = $.getUrlParam('reurl');

})(jQuery);

function changeInfo()
{
    $('#show').hide();
    $('#edit').show();

    $("#edit_number").val($("#number").val());
    $("#edit_name").val($("#name").val());
    $("#edit_sex").val($("#sex").val());
    $("#edit_idNumber").val($("#idNumber").val());
    $("#edit_birth").val($("#birth").val());
    $("#edit_nation").val($("#nation").val());
    $("#edit_level").val($("#level").val());
    $("#edit_place").val($("#place").val());
    $("#edit_postCode").val($("#postCode").val());
    $("#edit_status").val($("#status").val());
    $("#edit_phone").val($("#phone").val());
    $("#edit_mail").val($("#mail").val());
    $("#edit_studentType").val($("#studentType").val());
    $("#edit_studentProvince").val($("#studentProvince").val());
    $("#edit_middleSchool").val($("#middleSchool").val());
    $("#edit_date").val($("#date").val());




    $("#infoActive").empty();

    const save = '<button class="btn btn-small btn-primary" id="saveChange" onclick= "saveChange()">保存</button>';
    const cancel = '<button class="btn btn-small btn-warning" id="cancelChange" onclick= "cancelChange()">取消</button>';

    const $mode1 = $(save);
    const $mode2 = $(cancel);

    $("#infoActive").append($mode1);
    $("#infoActive").append($mode2);

    const url = getUrl();

    $.ajax({
        url:url+"adminInfo/getSelect",
        data:{},
        type: "get",
        contentType: "application/json",
        success: function(map) {
            console.log(map);


            if(map=="unLogin"){
                location.href="login.html";
            }else{
                $.each(map.colleges, function (i, college) {
                    console.log(college._name);
                    const option = '<option>'+college._name+'</option>';
                    const $obj = $(option);
                
                    $("#edit_college").append($obj);
                })
                $("#edit_college").val($("#college").val());
                $.each(map.majors, function (i, major) {
                    console.log(major._name);
                    const option = '<option>'+major._name+'</option>';
                    const $obj = $(option);
                
                    $("#edit_major").append($obj);
                })
                $("#edit_major").val($("#major").val());
                $.each(map.classes, function (i, _class) {
                    console.log(_class._name);
                    const option = '<option>'+_class._name+'</option>';
                    const $obj = $(option);
                
                    $("#edit_class").append($obj);
                })
                $("#edit_class").val($("#_class").val());
            }
        },
        error:function(){
            console.log("----------")
        }
    })
}

function saveChange()
{
    const index = $.getUrlParam('index');
    console.log(index);

    const map ={
        "index":index,
        "number":$("#edit_number").val(),
        "name":$("#edit_name").val(),
        "sex":$("#edit_sex").val(),
        "idNumber":$("#edit_idNumber").val(),
        "birth":$("#edit_birth").val(),
        "nation":$("#edit_nation").val(),
        "place":$("#edit_place").val(),
        "postCode":$("#edit_postCode").val(),
        "status":$("#edit_status").val(),
        "phone":$("#edit_phone").val(),
        "mail":$("#edit_mail").val(),
        "studentType":$("#edit_studentType").val(),
        "studentProvince":$("#edit_studentProvince").val(),
        "middleSchool":$("#edit_middleSchool").val(),
        "date":$("#edit_date").val(),
        "_class":$("#edit_class").val(),
        "level":$("#edit_level").val(),
        "college":$("#edit_college").val(),
        "major":$("#edit_major").val()
    }

    console.log(map);

    const url = getUrl();

    $.ajax({
        url:url+"adminInfo/changeInfo",
        data:JSON.stringify(map),
        type: "post",
        contentType: "application/json; charset=utf-8",
        success: function(id) {
            console.log(id);
            location.href="infoDetail.html?index="+id;
        },
        error:function(id){
            console.log("----------");
            console.log(id);
        }
    })
}

function cancelChange()
{
    $('#edit').hide();
    $('#show').show();

    $("#infoActive").empty();

    const change = '<button class="btn btn-small btn-inverse" id="changeInfo" onclick= "changeInfo()">修改</button>';

    const $mode = $(change);

    $("#infoActive").append($mode);
}

$("#selectPeer").click(function () {
    const url = getUrl();
    const peer = $("#peerSelect").val();
    console.log(peer);
    const index = $.getUrlParam('index');

    var pagenum =Number($("#page").val());
    const userId = new Date().getTime();

    if(peer=="当前节点"){

        location.href="infoDetail.html?index="+index;

    }else{

        var source = new EventSource(url + "adminInfo/getPeerData/"+userId);

        source.addEventListener('message', function (e) {
            console.log("在听了");
            console.log(e.data);
            map=JSON.parse(e.data);
            const d = map.data;

            console.log(map);

            if(map=="unLogin"){
                location.href="login.html";
            }else{

                $("#hash").val(map.hash);

                $("#number").val(d.number);
                $("#name").val(d.name);
                $("#sex").val(d.sex);
                $("#idNumber").val(d.idNumber);
                $("#birth").val(d.birth);
                $("#nation").val(d.nation);
                $("#_class").val(d._class);
                $("#level").val(d.level);
                $("#college").val(d.college);
                $("#place").val(d.place);
                $("#postCode").val(d.postCode);
                $("#status").val(d.status);
                $("#phone").val(d.phone);
                $("#mail").val(d.mail);
                $("#studentType").val(d.studentType);
                $("#studentProvince").val(d.studentProvince);
                $("#middleSchool").val(d.middleSchool);
                $("#date").val(d.date);
                $("#major").val(d.major);

                //$("#date").attr('placeholder',data.date);

                $.each(d.grades, function (i, grade) {
                    console.log(grade);

                    const mode = 
                    '<div class="row-fluid">'+
                        '<div class="span1">'+
                            '<div>'+
                                '<p id="id"></p>'+
                            '</div>'+
                        '</div>'+
                        '<div class="span2">'+
                            '<div>'+
                                '<input class="input-medium disabled" id="name" type="text" placeholder="" disabled="">'+
                            '</div>'+
                        '</div>'+
                        '<div class="span1">'+
                            '<div>'+
                                '<input class="input-mini disabled" id="credit" type="text" placeholder="" disabled="">'+
                            '</div>'+
                        '</div>'+
                        '<div class="span2">'+
                            '<div>'+
                                '<input class="input-medium disabled" id="type" type="text" placeholder="" disabled="">'+
                            '</div>'+
                        '</div>'+
                        '<div class="span2">'+
                            '<div>'+
                                '<input class="input-medium disabled" id="semester" type="text" placeholder="" disabled="">'+
                            '</div>'+
                        '</div>'+
                        '<div class="span2">'+
                            '<div>'+
                                '<input class="input-medium disabled" id="score" type="text" placeholder="" disabled="">'+
                            '</div>'+
                        '</div>'+
                        '<div class="span2" id="grade_active">'+
                        '</div>'+
                    '</div>';
                    
                    const $obj = $(mode);
                    $obj.find("#id").text(grade.id);
                    $obj.find("#name").val(grade.name);
                    $obj.find("#credit").val(grade.credit);
                    $obj.find("#type").val(grade.type);
                    $obj.find("#semester").val(grade.semester);
                    $obj.find("#score").val(grade.score);

                    $("#grade_body").append($obj);

                })
            }

        }, false);
    
        source.addEventListener('error', function (e) {
            console.log("异常：" + e.data);
        });

        const item ={
            "index":index,
            "userId":userId,
            "peer":peer
        }

        console.log(item);

        $.ajax({
            url:url+"adminInfo/sseSent",
            data:JSON.stringify(item),
            type: "post",
            contentType: "application/json; charset=utf-8",
            success: function(id) {
               
            },
            error:function(id){
               
            }
        })

    }
});

$(document).ready(function () {


    const index = $.getUrlParam('index');
    console.log(index);
    $('#edit').hide();

    const url = getUrl();

    $.ajax({
        url:url+"adminInfo/getDetail",
        data:{
            index:index
        },
        type: "get",
        contentType: "application/json",
        success: function(map) {
            console.log(map);

            data = map.data;

            if(map=="unLogin"){
                location.href="login.html";
            }else if(map.error=="true"){
                console.log("粗错了");
                showPage();
                $.each(map.ws, function (i, wsAdr) {
                    console.log(wsAdr);

                    const option = '<option>'+wsAdr+'</option>';

                    const $obj2 = $(option);

                    $("#peerSelect").append($obj2);
                })
            }else{
                $('#error').hide();
                $("#maxPage").val(map.maxPage);
                $("#page").val(map.page);

                $("#number").val(data.number);
                $("#name").val(data.name);
                $("#sex").val(data.sex);
                $("#idNumber").val(data.idNumber);
                $("#birth").val(data.birth);
                $("#nation").val(data.nation);
                $("#_class").val(data._class);
                $("#level").val(data.level);
                $("#college").val(data.college);
                $("#place").val(data.place);
                $("#postCode").val(data.postCode);
                $("#status").val(data.status);
                $("#phone").val(data.phone);
                $("#mail").val(data.mail);
                $("#studentType").val(data.studentType);
                $("#studentProvince").val(data.studentProvince);
                $("#middleSchool").val(data.middleSchool);
                $("#date").val(data.date);
                $("#major").val(data.major);

                //$("#date").attr('placeholder',data.date);
                showPage();

                if(!($.isEmptyObject(data.grades))){
                    $.each(data.grades, function (i, grade) {
                        console.log(grade);
    
                        const mode = 
                        '<div class="row-fluid">'+
                            '<div class="span1">'+
                                '<div>'+
                                    '<p id="id"></p>'+
                                '</div>'+
                            '</div>'+
                            '<div class="span2">'+
                                '<div>'+
                                    '<input class="input-medium disabled" id="name" type="text" placeholder="" disabled="">'+
                                '</div>'+
                            '</div>'+
                            '<div class="span1">'+
                                '<div>'+
                                    '<input class="input-mini disabled" id="credit" type="text" placeholder="" disabled="">'+
                                '</div>'+
                            '</div>'+
                            '<div class="span2">'+
                                '<div>'+
                                    '<input class="input-medium disabled" id="type" type="text" placeholder="" disabled="">'+
                                '</div>'+
                            '</div>'+
                            '<div class="span2">'+
                                '<div>'+
                                    '<input class="input-medium disabled" id="semester" type="text" placeholder="" disabled="">'+
                                '</div>'+
                            '</div>'+
                            '<div class="span2">'+
                                '<div>'+
                                    '<input class="input-medium disabled" id="score" type="text" placeholder="" disabled="">'+
                                '</div>'+
                            '</div>'+
                            '<div class="span2" id="grade_active">'+
                                '<div class="span6" id="changeGrade_">'+
                                    '<button class="btn btn-small btn-inverse" id="changeGrade" onclick= "">修改</button>'+
                                '</div>'+
                                '<div class="span6" id="deleteGrade_">'+
                                    '<button class="btn btn-small btn-danger" id="deleteGrade" onclick= "">删除</button>'+
                                '</div>'+
                            '</div>'+
                        '</div>';
                        
                        const $obj = $(mode);
                        $obj.find("#id").text(grade.id);
                        $obj.find("#name").val(grade.name);
                        $obj.find("#credit").val(grade.credit);
                        $obj.find("#type").val(grade.type);
                        $obj.find("#semester").val(grade.semester);
                        $obj.find("#score").val(grade.score);
    
                        $("#grade_body").append($obj);
    
                    })
                }

                $.each(map.ws, function (i, wsAdr) {
                    console.log(wsAdr);

                    const option = '<option>'+wsAdr+'</option>';

                    const $obj2 = $(option);

                    $("#peerSelect").append($obj2);
                })

            }

            
            
        },
        error:function(){
            console.log("----------")
        }
    })

    //点击成绩修改
    $("#grade_body").on('click','#changeGrade',function(){
        console.log("changeGrade");
        const id = $(this).parent().parent().parent().find("#id").text();
        console.log(id);

        
        $(this).parent().parent().parent().find("#semester").removeAttr("disabled");
        $(this).parent().parent().parent().find("#score").removeAttr("disabled");

        const save = '<div class="span6" id="confirmEdit_"><button class="btn btn-small btn-danger" id="confirmEdit">确认</button></div class="span6">';
        const cancel = '<div class="span6" id="cancelEdit_"><button class="btn btn-small btn-inverse" id="cancelEdit">取消</button></div class="span6">';

        const $mode1 = $(save);
        const $mode2 = $(cancel);

        $(this).parent().parent().append($mode1);
        $(this).parent().parent().append($mode2);
        $(this).parent().parent().find("#deleteGrade_").remove();
        $(this).parent().parent().find("#changeGrade_").remove();
        
        //getDetail(id);
    });

    //取消成绩修改
    $("#grade_body").on('click','#cancelEdit',function(){
        console.log("changeGrade");
        const id = $(this).parent().parent().parent().find("#id").text();
        console.log(id);

        
        $(this).parent().parent().parent().find("#semester").attr('disabled',"");
        $(this).parent().parent().parent().find("#score").attr('disabled',"");

        const save = '<div class="span6" id="changeGrade_"><button class="btn btn-small btn-inverse" id="changeGrade" onclick= "">修改</button></div>';
        const cancel = '<div class="span6" id="deleteGrade_"><button class="btn btn-small btn-danger" id="deleteGrade" onclick= "">删除</button></div>';

        const $mode1 = $(save);
        const $mode2 = $(cancel);

        $(this).parent().parent().append($mode1);
        $(this).parent().parent().append($mode2);
        $(this).parent().parent().find("#confirmEdit_").remove();
        $(this).parent().parent().find("#cancelEdit_").remove();
        
        //getDetail(id);
    });

    //确认成绩修改
    $("#grade_body").on('click','#confirmEdit',function(){
        const index = $.getUrlParam('index');
        console.log(index);

        const map ={
            "index":index,
            "id":$(this).parent().parent().parent().find("#id").text(),
            "name":$(this).parent().parent().parent().find("#name").val(),
            "credit":$(this).parent().parent().parent().find("#credit").val(),
            "type":$(this).parent().parent().parent().find("#type").val(),
            "semester":$(this).parent().parent().parent().find("#semester").val(),
            "score":$(this).parent().parent().parent().find("#score").val()
        }

        console.log(map);

        $.ajax({
            url:url+"adminInfo/editGrade",
            data:JSON.stringify(map),
            type: "post",
            contentType: "application/json; charset=utf-8",
            success: function(id) {
                console.log(id);
                location.href="infoDetail.html?index="+id;
            },
            error:function(id){
                console.log("----------");
                console.log(id);
            }
        })
        
    });

    //取消添加成绩
    $("#grade_body").on('click','#cancelGrade',function(){
        $("#grade_input").remove();
    });

    //添加成绩
    $("#grade_body").on('click','#addGrade',function(){
        const index = $.getUrlParam('index');
        const map ={
            "index":index,
            "name":$("#input_name").find("option:selected").text(),
            "credit":$("#input_credit").val(),
            "type":$("#input_type").val(),
            "semester":$("#input_semester").val(),
            "score":$("#input_score").val()
        }
    
        console.log(map);
    
    
        $.ajax({
            url:url+"adminInfo/addGrade",
            data:JSON.stringify(map),
            type: "post",
            contentType: "application/json; charset=utf-8",
            success: function(id) {
                console.log(id);
                location.href="infoDetail.html?index="+id;
            },
            error:function(id){
                console.log("----------");
                console.log(id);
            }
        })
        
    });

    //点击成绩删除
    $("#grade_body").on('click','#deleteGrade',function(){
        

        const save = '<div class="span6" id="confirmDelete_"><button class="btn btn-small btn-danger" id="confirmDelete">确认</button></div class="span6">';
        const cancel = '<div class="span6" id="cancelDelete_"><button class="btn btn-small btn-inverse" id="cancelDelete">取消</button></div class="span6">';

        const $mode1 = $(save);
        const $mode2 = $(cancel);

        $(this).parent().parent().append($mode1);
        $(this).parent().parent().append($mode2);
        $(this).parent().parent().find("#changeGrade_").remove();
        $(this).parent().parent().find("#deleteGrade_").remove();
        
    });

    //取消成绩删除
    $("#grade_body").on('click','#cancelDelete',function(){
        

        const save = '<div class="span6" id="changeGrade_"><button class="btn btn-small btn-inverse" id="changeGrade" onclick= "">修改</button></div>';
        const cancel = '<div class="span6" id="deleteGrade_"><button class="btn btn-small btn-danger" id="deleteGrade" onclick= "">删除</button></div>';

        const $mode1 = $(save);
        const $mode2 = $(cancel);

        $(this).parent().parent().append($mode1);
        $(this).parent().parent().append($mode2);
        $(this).parent().parent().find("#confirmDelete_").remove();
        $(this).parent().parent().find("#cancelDelete_").remove();
        
    });

    //确认成绩删除
    $("#grade_body").on('click','#confirmDelete',function(){
        const id = $(this).parent().parent().parent().find("#id").text();
        console.log(id);
        const index = $.getUrlParam('index');
        console.log(index);

        const map ={
            "id":id,
            "index":index
        }

        $.ajax({
            url:url+"adminInfo/deleteGrade",
            data:JSON.stringify(map),
            type: "post",
            contentType: "application/json; charset=utf-8",
            success: function(id) {
                console.log(id);
                location.href="infoDetail.html?index="+id;
            },
            error:function(id){
                console.log("----------");
                console.log(id);
            }
        })
        
    });

    $("#grade_body").on('change','#input_name',function(){
        const id = $("#input_name").val();
        console.log(id);
        $.ajax({
            url:url+"adminInfo/selectCourse",
            data:{
                index:id
            },
            type: "get",
            contentType: "application/json",
            success: function(map) {
                console.log(map);
    
    
                if(map=="unLogin"){
                    location.href="login.html";
                }else{
                    $("#input_credit").val(map.credit);
                    $("#input_type").val(map.type);
                }
            },
            error:function(){
                console.log("----------")
            }
        })
    })

    
});


//点击添加成绩
$("#add_grade").click(function () {
    const mode = 
                '<div class="row-fluid" id="grade_input">'+
					'<div class="span1">'+
                        '<div>'+
                            
                        '</div>'+
					'</div>'+
					'<div class="span2">'+
						'<div>'+
                            '<select id="input_name" style="width: 160px;">'+
                            '</select>	'+
						'</div>'+
					'</div>'+
					'<div class="span1">'+
						'<div>'+
							'<input class="input-mini disabled" id="input_credit" type="text" placeholder="">'+
						'</div>'+
					'</div>'+
					'<div class="span2">'+
						'<div>'+
							'<input class="input-medium disabled" id="input_type" type="text" placeholder="">'+
						'</div>'+
					'</div>'+
					'<div class="span2">'+
						'<div>'+
							'<input class="input-medium disabled" id="input_semester" type="text" placeholder="">'+
						'</div>'+
					'</div>'+
					'<div class="span2">'+
						'<div>'+
							'<input class="input-medium disabled" id="input_score" type="text" placeholder="">'+
						'</div>'+
					'</div>'+
					'<div class="span2">'+
						'<div class="span6">'+
							'<button class="btn btn-small btn-inverse" id="addGrade">添加</button>'+
						'</div>'+
						'<div class="span6">'+
							'<button class="btn btn-small btn-danger" id="cancelGrade">取消</button>'+
						'</div>'+
					'</div>'+
				'</div>';
                
    const $obj = $(mode);
    console.log($("#grade_input").length)
    if($("#grade_input").length==0){
        $("#grade_title").after($obj);
        const url = getUrl();

        $.ajax({
            url:url+"adminInfo/listCourse",
            data:{},
            type: "get",
            contentType: "application/json",
            success: function(data) {
                if(data=="unLogin"){
                    location.href="login.html";
                }else{
                    if(!($.isEmptyObject(data))){
                        $.each(data, function (i, course) {
                            console.log(course);
                            const option = '<option'+' value ="'+course.id+'">'+course._name+'</option>';

                            const $obj = $(option);

                            $("#input_name").append($obj);
                        })
                        $("#input_credit").val(data[0].credit);
                        $("#input_type").val(data[0].type);
                    }
                }
            },
            error:function(){
                console.log("----------")
            }
        })
    }
});

function showPage(){
    $("#pageActive").empty();

    const page1 =
    '<div class="span2">'+
		'<h3 id="prePage">< 上一记录</h3>'+
	'</div>'+
    '<div class="span9"></div>'+
    '<div class="span1">'+
		'<h3 id="nextPage">下一记录 ></h3>'+
	'</div>';

    const page2 =
    '<div class="span2">'+
	'</div>'+
    '<div class="span9"></div>'+
    '<div class="span1">'+
		'<h3 id="nextPage">下一记录 ></h3>'+
	'</div>';

    const page3 =
    '<div class="span2">'+
		'<h3 id="prePage">< 上一记录</h3>'+
	'</div>'+
    '<div class="span9"></div>'+
    '<div class="span1">'+
	'</div>';

    const page4 =
    '<div class="span2">'+
	'</div>'+
    '<div class="span9"></div>'+
    '<div class="span1">'+
	'</div>';

    const $p1 = $(page1);
    const $p2 = $(page2);
    const $p3 = $(page3);
    const $p4 = $(page4);

    var pagenum =$("#page").val();
    var pageMax =$("#maxPage").val();
    console.log(pagenum);
    console.log(pageMax);
    if(pageMax==1){
        $("#pageActive").append($p4);
    }else if(pagenum==pageMax){
        $("#pageActive").append($p3);
    }else if(pagenum==1){
        $("#pageActive").append($p2);
    }else{
        $("#pageActive").append($p1);
    }
}

$("#pageActive").on('click','#prePage',function(){
    var pagenum =Number($("#page").val())-1;
    $("#page").val(pagenum);
    const index = $.getUrlParam('index');
    
    const url = getUrl();
    const map ={
        page:pagenum,
        index:index
    }

    $.ajax({
        url:url+"adminInfo/getDataByPage",
        data:JSON.stringify(map),
        type: "post",
        contentType: "application/json",
        success: function(id) {
            console.log(id);
            location.href="infoDetail.html?index="+id;
        },
        error:function(){
            console.log("----------")
        }
    })
});


$("#pageActive").on('click','#nextPage',function(){
    var pagenum =Number($("#page").val())+1;
    $("#page").val(pagenum);
    const index = $.getUrlParam('index');
    
    const url = getUrl();
    const map ={
        page:pagenum,
        index:index
    }

    $.ajax({
        url:url+"adminInfo/getDataByPage",
        data:JSON.stringify(map),
        type: "post",
        contentType: "application/json",
        success: function(id) {
            console.log(id);
            location.href="infoDetail.html?index="+id;
            
        },
        error:function(){
            console.log("----------")
        }
    })
});